﻿using UnityEngine;
using System.Collections;

public class timedMove : MonoBehaviour
{
    private float t, timer, q;

    public Vector3 startPosition;
    public Vector3 endPosition;//start 0, -4.8 , 1.5 end 0, -6, 1.5
    public float time = 120f;
    private GameObject backgroundSync;
    private backgroundfade background;
    private float initialAlpha;
    private float realAlpha;
    // Use this for initialization
    void Start()
    {
        backgroundSync = GameObject.Find("Background");
        background = backgroundSync.GetComponent<backgroundfade>();

        initialAlpha = background.aValue;
        startPosition = transform.position;
        StartCoroutine(MoveToPosition());
    }

    // Update is called once per frame
    void Update()
    {
        realAlpha = background.aValue;
        q += Time.deltaTime;
        if (background.aValue != initialAlpha)
        {
            initialAlpha = background.aValue;
            renderer.enabled = true;
            endPosition = startPosition;
            startPosition = transform.position;
            StartCoroutine(MoveToPosition());
        }
    }

    public IEnumerator MoveToPosition()
    {
        t = 0;
        while (t < 1)
        {
            t += Time.deltaTime / (time/*background.aTime*background.transform.childCount+1*/);
            transform.position = Vector3.Lerp(startPosition, endPosition, t);
            yield return null;
        }
//        if (background.aValue == 0)
//        {
//            renderer.enabled = false;
//        }
		if(transform.position == endPosition)
		{
			renderer.enabled = false;
		}

    }



    
//    void Move()
//    {
//        // t = Mathf.Clamp01(Time.deltaTime + t);
//        //Mathf.Clamp(timer, 0, t);
//        //transform.position = Vector3.MoveTowards(transform.position, endPosition, timer); //about 1 sec off
//        //transform.position = new Vector3(transform.position.x, transform.position.y + Mathf.PingPong(Time.time, 6.3f), transform.position.z);
//
//        t += Time.deltaTime / time;
//        transform.position = Vector3.Lerp(transform.position, endPosition, t);
//        if (transform.position == endPosition)
//        {
//            print(q);
//            if (background.aValue == 0)
//            {
//                renderer.enabled = true;
//            }
//            if (background.aValue != initialAlpha)
//            {
//                initialAlpha = background.aValue;
//                renderer.enabled = true;
//                endPosition = startPosition;
//                startPosition = transform.position;
//            }
//        }
//    }
}

